﻿(function ($) {
    $.advSearch = $.advSearch || {};
    $.extend($.advSearch, {
        getAccessor: function (obj, expr) {
            var ret, p, prm = [], i;
            if (typeof expr === 'function') { return expr(obj); }
            ret = obj[expr];
            if (ret === undefined) {
                try {
                    if (typeof expr === 'string') {
                        prm = expr.split('.');
                    }
                    i = prm.length;
                    if (i) {
                        ret = obj;
                        while (ret && i--) {
                            p = prm.shift();
                            ret = ret[p];
                        }
                    }
                } catch (e) { }
            }
            return ret;
        },
        extend: function (methods) {
            $.extend($.fn.advSearch, methods);
            if (!this.no_legacy_api) {
                $.fn.extend(methods);
            }
        }
    });
    $.fn.advSearch = function (pin) {
        if (typeof pin == 'string') {
            //var fn = $.fn.jqGrid[pin];
            var fn = $.advSearch.getAccessor($.fn.advSearch, pin);
            if (!fn) {
                throw ("jqGrid - No such method: " + pin);
            }
            var args = $.makeArray(arguments).slice(1);
            return fn.apply(this, args);
        };

        //create div groups

        var ash = $("<div id='as_header'></div>");
        var asf = $("<div id='as_footer'></div>");
        var asr = $("<div id='as_rows'></div>");

        ash.append("<select id='as_andor'><option value='&&' selected='selected'>AND</option><option value='||'>OR</option></select><button id='as_add'>+ add</button>");
        ash.append("<select id='as_quicksearch'><option value=''>select a predefined quick search</option></select>");
        asf.append("<button id='as_reset'>Reset</button><button id='as_search'>Find</button>");
        this.append(ash);
        ash.append(asf);
        this.append(asr);

        $('#as_add').click(function () {
            jQuery("#advancedsearch").addRow();
            return false;
        });
        $('#as_reset').click(function () {
            jQuery("#advancedsearch").clearParams();
            var andor = $('#as_andor').val();
            jQuery("#advancedsearch").initParam(andor);
            $('#as_rows').html('');
            jQuery("#advancedsearch").addRow();
            resizeGrid();
            $("#list").setGridParam({ page: 1 });
            var grid = $("#list");
            grid[0].clearToolbar();
            $("#list").trigger("reloadGrid");
            return false;
        });
        $('#as_search').click(function () {
            jQuery("#advancedsearch").clearParams();
            var andor = $('#as_andor').val();
            jQuery("#advancedsearch").initParam(andor);
            var rowcount = 0;
            $('#as_rows div.as_row').each(function () {
                rowcount++;
                var selatype = $(this).find('select.as_type');
                var acolumn = $(this).find('select.as_type').val();
                var atype = $(this).find('select.as_type option:selected').attr('dt');
                var aoperator = $(this).find('select.as_condition').val();
                var avalue0 = $(this).find('input.as_value0').val();
                var avalue1 = $(this).find('input.as_value1').val();
                var avalue2 = $(this).find('input.as_value2').val();
                var avalue3 = $(this).find('select.as_value3').val();
                if (avalue3 == null) { avalue3 = ""; }
                if ((acolumn.length < 0) || (aoperator == null) || (aoperator.length < 0)) {
                    var aval = $(this).find('.as_subt').trigger('click');
                    rowcount--;
                }
                else {
                    var param = { column: acolumn, datatype: atype, operator: aoperator, value0: avalue0, value1: avalue1, value2: avalue2, value3: avalue3 };
                    jQuery("#advancedsearch").addParam(param);
                }
            });
            if (rowcount <= 0) {
                jQuery("#advancedsearch").addRow();
            }
            resizeGrid();
            $("#list").setGridParam({ page: 1 });
            $("#list").trigger("reloadGrid");
            return false;
        });


        return this.each(function () {
            if (this.searchrow) { return; }
            var p = $.extend(true, {
                colNames: {},
                colTypes: {},
                typeOptions: { "int":
                                    [{ "name": "equal", "convert": "=={0}", "cindex": "0", "valstat": "show0" }, { "name": "not equal", "convert": "<>{0}", "cindex": "1", "valstat": "show0" }, { "name": "less", "convert": "<{0}", "cindex": "2", "valstat": "show0" }, { "name": "less or equal", "convert": "<={0}", "cindex": "3", "valstat": "show0" }, { "name": "greater", "convert": ">{0}", "cindex": "4", "valstat": "show0" }, { "name": "greater or equal", "convert": ">={0}", "cindex": "5", "valstat": "show0"}],
                    "dec":
                                    [{ "name": "equal", "convert": "=={0}", "cindex": "0", "valstat": "show0" }, { "name": "not equal", "convert": "<>{0}", "cindex": "1", "valstat": "show0" }, { "name": "less", "convert": "<{0}", "cindex": "2", "valstat": "show0" }, { "name": "less or equal", "convert": "<={0}", "cindex": "3", "valstat": "show0" }, { "name": "greater", "convert": ">{0}", "cindex": "4", "valstat": "show0" }, { "name": "greater or equal", "convert": ">={0}", "cindex": "5", "valstat": "show0" }, { "name": "is null", "convert": "==null", "cindex": "6", "valstat": "dis0" }, { "name": "is not null", "convert": "!==null", "cindex": "7", "valstat": "dis0"}],
                    "intstr":
                                    [{ "name": "equal", "convert": "=={0}", "cindex": "0", "valstat": "show0" }, { "name": "not equal", "convert": "<>{0}", "cindex": "1", "valstat": "show0" }, { "name": "less", "convert": "<{0}", "cindex": "2", "valstat": "show0" }, { "name": "less or equal", "convert": "<={0}", "cindex": "3", "valstat": "show0" }, { "name": "greater", "convert": ">{0}", "cindex": "4", "valstat": "show0" }, { "name": "greater or equal", "convert": ">={0}", "cindex": "5", "valstat": "show0" }, { "name": "is null", "convert": "==\"\"", "cindex": "8", "valstat": "dis0" }, { "name": "is not null", "convert": "!==\"\"", "cindex": "9", "valstat": "dis0" }, { "name": "begins with", "convert": ".StartsWith({0})", "cindex": "10", "valstat": "show0" }, { "name": "does not begin with", "convert": "!.StartsWith({0})", "cindex": "11", "valstat": "show0" }, { "name": "ends with", "convert": ".EndsWith({0})", "cindex": "12", "valstat": "show0" }, { "name": "does not end with", "convert": "!.EndsWith({0})", "cindex": "13", "valstat": "show0" }, { "name": "contains", "convert": ".Contains({0})", "cindex": "14", "valstat": "show0" }, { "name": "does not contain", "convert": "!.Contains({0})", "cindex": "15", "valstat": "show0"}],
                    "str":
                                    [{ "name": "equal", "convert": "=={0}", "cindex": "0", "valstat": "show0" }, { "name": "not equal", "convert": "<>{0}", "cindex": "1", "valstat": "show0" }, { "name": "begins with", "convert": ".StartsWith({0})", "cindex": "10", "valstat": "show0" }, { "name": "does not begin with", "convert": "!.StartsWith({0})", "cindex": "11", "valstat": "show0" }, { "name": "ends with", "convert": ".EndsWith({0})", "cindex": "12", "valstat": "show0" }, { "name": "does not end with", "convert": "!.EndsWith({0})", "cindex": "13", "valstat": "show0" }, { "name": "contains", "convert": ".Contains({0})", "cindex": "14", "valstat": "show0" }, { "name": "does not contain", "convert": "!.Contains({0})", "cindex": "15", "valstat": "show0" }, { "name": "is null", "convert": "==\"\"", "cindex": "8", "valstat": "dis0" }, { "name": "is not null", "convert": "!==\"\"", "cindex": "9", "valstat": "dis0"}],
                    "cbo":
                                    [{ "name": "equal", "convert": "=={3}", "cindex": "23", "valstat": "show3" }, { "name": "not equal", "convert": "<>{3}", "cindex": "24", "valstat": "show3" }, { "name": "is null", "convert": "==\"\"", "cindex": "8", "valstat": "dis3" }, { "name": "is not null", "convert": "!==\"\"", "cindex": "9", "valstat": "dis3"}],
                    "yn":
                                    [{ "name": "equal", "convert": "=={3}", "cindex": "23", "valstat": "show3"}],
                    "date":
                                    [{ "name": "equal", "convert": "?{1}{1}", "cindex": "16", "valstat": "show1" }, { "name": "not equal", "convert": "!?{1}{1}", "cindex": "17", "valstat": "show1" }, { "name": "less", "convert": " < Convert.ToDateTime(\"{1} 12:00:00 AM\")", "cindex": "18", "valstat": "show1" }, { "name": "less or equal", "convert": " <= Convert.ToDateTime(\"{1} 11:59:59 PM\")", "cindex": "19", "valstat": "show1" }, { "name": "greater", "convert": " > Convert.ToDateTime(\"{1} 11:59:59 PM\")", "cindex": "20", "valstat": "show1" }, { "name": "greater or equal", "convert": " >= Convert.ToDateTime(\"{1} 12:00:00 AM\")", "cindex": "21", "valstat": "show1" }, { "name": "is null", "convert": "<=Convert.ToDateTime(\"01/02/0001 12:00:00 AM\")", "cindex": "25", "valstat": "dis0" }, { "name": "is not null", "convert": ">Convert.ToDateTime(\"01/02/0001 12:00:00 AM\")", "cindex": "26", "valstat": "dis0" }, { "name": "is between", "convert": "?{1}{2}", "cindex": "22", "valstat": "show12"}]
                },
                typeConverstions: { "0": "=={0}", "1": "<>{0}", "2": "<{0}", "3": "<={0}", "4": ">{0}", "5": ">={0}", "6": "==null", "7": "!==null", "8": "==\"\"", "9": "!==\"\"", "10": ".StartsWith({0})", "11": "!.StartsWith({0})", "12": ".EndsWith({0})", "13": "!.EndsWith({0})", "14": ".Contains({0})", "15": "!.Contains({0})", "16": "?{1}{1}", "17": "!?{1}{1}", "18": " < Convert.ToDateTime(\"{1} 12:00:00 AM\")", "19": " <= Convert.ToDateTime(\"{1} 11:59:59 PM\")", "20": " > Convert.ToDateTime(\"{1} 11:59:59 PM\")", "21": " >= Convert.ToDateTime(\"{1} 12:00:00 AM\")", "22": "?{1}{2}", "23": "=={3}", "24": "<>{3}", "25": "<=Convert.ToDateTime(\"01/02/0001 12:00:00 AM\")", "26": ">Convert.ToDateTime(\"01/02/0001 12:00:00 AM\")" },
                params: { andor: '&&', items: [] }
            }, $.advSearch.defaults, pin || {});
            var searchrow = {};
            this.p = p;

        });


    };

    $.advSearch.extend({
        addRow: function (param) {
            var $t = this[0];
            var wpr = $("<div class='as_row'></div>");
            var ddtype = $("<select class='as_type'><option value=''>select a column</option></select>");
            var ddcondition = $("<select class='as_condition' disabled></select>");
            var txtvalue = $("<div class='as_values'><input class='as_value0' type='text'  disabled/><input class='as_value1 dtpkr' type='text'/><input class='as_value2 dtpkr' type='text'/><select class='as_value3'></select></div>");
            var btnsubt = $("<button class='as_subt'>-</button>");
            var cnames = $t.p.colNames;

            cnames.sort(function compareDisp(a, b) {
                var aDisp = a.disp.toUpperCase();
                var bDisp = b.disp.toUpperCase();
                return ((aDisp < bDisp) ? -1 : ((aDisp > bDisp) ? 1 : 0));
            });

            var ctypo = $t.p.typeOptions;
            for (i = 0; i < cnames.length; i++) {
                if (cnames[i].valu.length > 0) {
                    $(ddtype).append(
                        '<option value="'
                        + cnames[i].valu
                        + '" dt="'
                        + cnames[i].typ
                        + '">'
                        + cnames[i].disp
                        + '</option>'
                    );
                }
            }
            $(wpr).append(ddtype);
            $(wpr).append(ddcondition);
            $(wpr).append(txtvalue);

            $(wpr).append(btnsubt);

            $('#as_rows').append(wpr);
            $(this).find('.as_subt').click(function () {
                row = $(this).parents('div.as_row');
                row.remove();
                return false;
            });
            $(this).find('.as_type').change(function () {
                row = $(this).parents('div.as_row');
                var cond = $(row).find('select.as_condition')[0];
                var ival0 = $(row).find('input.as_value0')[0];
                var ival1 = $(row).find('input.as_value1')[0];
                var ival2 = $(row).find('input.as_value2')[0];
                var ival3 = $(row).find('select.as_value3')[0];

                //$(cond).attr('disabled', 'disabled');
                var seltyp = $(this).val();
                var typ = $(this).find('option:selected').attr('dt');
                var opts = ctypo[typ];
                $(cond).attr('disabled', 'disabled');
                $(ival0).val('');
                $(ival1).val('');
                $(ival2).val('');
                $(ival3).val('');
                $(ival0).hide();
                $(ival1).hide();
                $(ival2).hide();
                $(ival3).hide();
                $(cond).show();

                switch (typ) {
                    case 'date':
                        $(ival1).show();
                        break;
                    case 'cbo':
                        $(ival3).find('option').remove().end();
                        $(ival3).append("<option value=''>select a value</option>");

                        for (var x = 0; x < cnames.length; x++) {
                            if (cnames[x].valu == seltyp) {
                                for (var y = 0; y < cnames[x].srchop.length; y++) {
                                    var addoptval = cnames[x].srchop[y];
                                    var addopt = "<option value='" + addoptval.toLowerCase() + "'>" + addoptval + "</option>";
                                    $(ival3).append(addopt);
                                }
                                x = cnames.length;
                            }
                        }
                        $(ival3).show();
                        break;
                    case 'yn':
                        $(ival3).find('option').remove().end();
                        $(ival3).append("<option value='Y'>YES</option>");
                        $(ival3).append("<option value='N'>NO</option>");
                        $(ival3).show();
                        break;
                    case 'dec':
                        $(ival0).show();
                        $(ival0).removeAttr('disabled');
                        $(ival0).attr("isnumber", "no");
                        $(ival0).attr("isdecimal", "yes");
                        break;
                    case 'int':
                        $(ival0).show();
                        $(ival0).removeAttr('disabled');
                        $(ival0).attr("isnumber", "yes");
                        break;
                    default:
                        $(ival0).show();
                        $(ival0).removeAttr('disabled');
                        $(ival0).attr("isnumber", "no");
                        break;
                }

                if ((opts != null) && (opts.length > 0)) {

                    $(cond).find('option').remove().end();
                    for (var i = 0; i < opts.length; i++) {
                        var optn = "<option value='" + opts[i].cindex + "' vs=" + opts[i].valstat + ">" + opts[i].name + "</option>";
                        $(cond).append(optn);
                    }
                    if (typ != 'yn') {
                        $(cond).removeAttr('disabled');
                    }


                }
                $(".dtpkr").datepicker({ dateFormat: 'yy-mm-dd' });
                $(row).find('input[isnumber="yes"]').keydown(function () {
                    var isnum = $(this).attr("isnumber");
                    if (isnum == "yes") {
                        if (!(event.keyCode == 8                            // backspace
                        || event.keyCode == 46                              // delete
                        || (event.keyCode >= 35 && event.keyCode <= 40)     // arrow keys/home/end
                        || (event.keyCode >= 48 && event.keyCode <= 57)     // numbers on keyboard
                        || (event.keyCode >= 96 && event.keyCode <= 105))   // number on keypad
                        ) {
                            event.returnValue = false;   // Prevent character input
                        }
                    }
                });
                $(row).find('input[isdecimal="yes"]').keydown(function () {
                    var isnum = $(this).attr("isdecimal");
                    if (isnum == "yes") {
                        if (!(event.keyCode == 8                            // backspace
                        || event.keyCode == 46                              // delete
                        || event.keyCode == 110 || event.keyCode == 231     // decimal point
                        || (event.keyCode >= 35 && event.keyCode <= 40)     // arrow keys/home/end
                        || (event.keyCode >= 48 && event.keyCode <= 57)     // numbers on keyboard
                        || (event.keyCode >= 96 && event.keyCode <= 105))   // number on keypad
                        ) {
                            event.returnValue = false;   // Prevent character input
                        }
                    }
                });
                $(row).find('input').keydown(function () {
                    if (event.keyCode == 13) {
                        $('#as_search').click();
                    }
                });

                return false;
            });
            $(this).find('.as_condition').change(function () {
                row = $(this).parents('div.as_row');
                //var typ = $(row).find('select.as_type option:selected').attr('dt');
                var vasstat = $(this).find('option:selected').attr('vs');
                var ival0 = $(row).find('input.as_value0')[0];
                var ival1 = $(row).find('input.as_value1')[0];
                var ival2 = $(row).find('input.as_value2')[0];
                var ival3 = $(row).find('select.as_value3')[0];
                switch (vasstat) {
                    case 'show0':
                        $(ival0).show();
                        $(ival1).hide();
                        $(ival2).hide();
                        $(ival3).hide();
                        $(ival0).removeAttr('disabled');
                        $(ival0).focus();
                        break;
                    case 'show1':
                        $(ival0).hide();
                        $(ival1).show();
                        $(ival2).hide();
                        $(ival3).hide();
                        //$(ival1).focus();
                        break;
                    case 'show3':
                        $(ival0).hide();
                        $(ival1).hide();
                        $(ival2).hide();
                        $(ival3).show();
                        $(ival3).removeAttr('disabled');
                        $(ival3).focus();
                        break;
                    case 'dis0':
                        $(ival0).show();
                        $(ival1).hide();
                        $(ival2).hide();
                        $(ival3).hide();
                        $(ival0).attr('disabled', 'disabled');
                        break;
                    case 'dis3':
                        $(ival0).hide();
                        $(ival1).hide();
                        $(ival2).hide();
                        $(ival3).show();
                        $(ival3).val("");
                        $(ival3).attr('disabled', 'disabled');
                        break;
                    case 'show12':
                        $(ival0).hide();
                        $(ival1).show();
                        $(ival2).show();
                        $(ival3).hide();
                        break;
                    default:
                        break;
                }
                return false;
            });
            $(wpr).find('input.as_value1').hide();
            $(wpr).find('input.as_value2').hide();
            $(wpr).find('select.as_value3').hide();
            if (param != null) {
                var par_type = $(wpr).find('select.as_type');
                var cond = $(wpr).find('select.as_condition');
                if (param.column != null) {
                    $(par_type).val(jQuery.trim(param.column));
                    $(par_type).trigger('change');
                }
                if (param.operator != null) {
                    $(cond).val(jQuery.trim(param.operator));
                    $(cond).trigger('change');
                }
                if (param.value0 != null) {
                    $(wpr).find('input.as_value0').val(jQuery.trim(param.value0.toLowerCase()));
                }
                if (param.value1 != null) {
                    $(wpr).find('input.as_value1').val(jQuery.trim(param.value1.toLowerCase()));
                }
                if (param.value2 != null) {
                    $(wpr).find('input.as_value2').val(jQuery.trim(param.value2.toLowerCase()));
                }
                if (param.value3 != null) {
                    $(wpr).find('select.as_value3').val(jQuery.trim(param.value3.toLowerCase()));
                }
            }

        },
        initParam: function (andor) {
            var $t = this[0];
            $t.p.params.andor = andor;
            $t.p.params.items = [];
        },
        addParam: function (param) {
            var $t = this[0];
            $t.p.params.items.push(param);
        },
        clearParams: function () {
            var $t = this[0];
            $t.p.params = {};
        }
    });

    $.advSearch.p = {
        colNames: {},
        colTypes: {},
        typeOptions: {},
        params: [],
        andor: 'AND'
    };

})(jQuery);

